package com.example.spring.test;

import java.util.LinkedList;
import java.util.Queue;

public class WaitNotify {

    private final static int CONTAINER_MAX_LENGTH = 3;

    private static Queue<Integer> resources = new LinkedList<Integer>();

    //作为synchronized的对象监视器
    private static final Object lock = new Object();

    /**
     * 消费者
     */
    static class Consumer implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                while (resources.isEmpty()) {
                    //当前释放锁，线程进入等待状态
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "get number is" + resources.poll());
                //唤醒所有等待状态的线程
            }
        }
    }

    /**
     * 生产者
     */
    static class Producer implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                while (resources.size() == CONTAINER_MAX_LENGTH) {
                    //当前释放锁，线程进入等待状态
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int number = (int) (Math.random() * 100);
                System.out.println(Thread.currentThread().getName() + " produce number is " + number);
                resources.offer(number);
                lock.notifyAll();
            }
        }
    }


    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            new Thread(new Consumer(), "consumer-" + i).start();
        }

        for (int i = 0; i < 50; i++) {
            new Thread(new Producer(), "producer-" + i).start();
        }
    }

}

